<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文介绍FreeRTOS软件定时器的实现原理。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-软件定时器的实现原理">
<meta property="og:url" content="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="本文介绍FreeRTOS软件定时器的实现原理。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/timer-task-schema.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/timer-list.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/timer_wait_queue.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/timer_wait_queue_or_timeout.png">
<meta property="article:published_time" content="2022-11-26T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-08T14:21:36.131Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/timer-task-schema.png">


<link rel="canonical" href="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/","path":"2022/11/27/FreeRTOS-principle_of_timer/","title":"FreeRTOS-软件定时器的实现原理"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-软件定时器的实现原理 | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E8%BD%AF%E4%BB%B6%E5%AE%9A%E6%97%B6%E5%99%A8%E7%9A%84%E6%95%B4%E4%BD%93%E9%80%BB%E8%BE%91"><span class="nav-number">1.</span> <span class="nav-text">1 软件定时器的整体逻辑</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E5%86%85%E6%A0%B8%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%9C%A8%E8%AE%BE%E7%BD%AE%E7%9A%84%E8%B6%85%E6%97%B6%E5%8F%91%E7%94%9F%E5%90%8E%EF%BC%8C%E8%B0%83%E7%94%A8%E8%AE%BE%E7%BD%AE%E7%9A%84%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0"><span class="nav-number">2.</span> <span class="nav-text">2 内核如何实现在设置的超时发生后，调用设置的回调函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%80%BB%E7%BB%93%EF%BC%9A"><span class="nav-number">3.</span> <span class="nav-text">总结：</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-软件定时器的实现原理 | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-软件定时器的实现原理
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-11-27 00:00:00" itemprop="dateCreated datePublished" datetime="2022-11-27T00:00:00+08:00">2022-11-27</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.6k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>7 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
本文介绍FreeRTOS软件定时器的实现原理。
</center>
<span id="more"></span>

<hr>
<p>FreeRTOS的软件定时器实际使用，可以参考：<a href="https://fengxun2017.github.io/2022/11/16/FreeRTOS-use-timer/">FreeRTOS-软件定时器的使用</a></p>
<h4 id="1-软件定时器的整体逻辑"><a href="#1-软件定时器的整体逻辑" class="headerlink" title="1 软件定时器的整体逻辑"></a>1 软件定时器的整体逻辑</h4><p>FreeRTOS的软件定时器不依赖于任何额外的硬件定时器，完全由内核通过软件来实现的。<br>使用FreeRTOS 的软件定时器（timer）,需要在工程中包含 <code>FreeRTOS/Source/timers.c</code>文件，并且在<code>FreeRTOSConfig.h</code>文件中添加宏：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configUSE_TIMERS				1</span></span><br></pre></td></tr></table></figure>
<p>一旦配置了宏<code>configUSE_TIMERS = 1</code>，在调用 启动内核调度API：<code>vTaskStartScheduler</code>时，该函数内部会创建一个名为<strong>xTimerQueue</strong>的消息队列和一个名为<strong>prvTimerTask</strong>的定时器服务任务（timer.c文件中）：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">vTaskStartScheduler</span><span class="params">( <span class="type">void</span> )</span> &#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="meta">#<span class="keyword">if</span> ( configUSE_TIMERS == 1 )</span></span><br><span class="line">        <span class="comment">// 该函数内部会创建软件定时器需要的资源，</span></span><br><span class="line">        <span class="comment">// 如消息队列xTimerQueue，定时器服务任务prvTimerTask 等</span></span><br><span class="line">        xReturn = xTimerCreateTimerTask();</span><br><span class="line">    <span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>xTimerQueue</strong>：为软件定时器模块专用的消息队列。</li>
<li><strong>prvTimerTask</strong>：软件定时器服务任务，该任务创建后，就会一直存在。该任务会从消息队列<strong>xTimerQueue</strong>中提取消息，并处理消息中包含的软件定时器相关命令</li>
</ul>
<p>调用FreeRTOS的软件定时器相关API时，实际是发送了相关的命令到消息队列<strong>xTimerQueue</strong>中（例如，调用<code>xTimerStart</code>启动某个定时器时，实际是将 start命令和要启动的定时器句柄，封装成一个消息体，并发送到消息队列xTimerQueue中。 ），<strong>prvTimerTask</strong>任务则从消息队列<strong>xTimerQueue</strong>中提取消息，解析相关命令并执行对应处理。</p>
<p>如下图所示：在自定义任务app_task中，使用软件定时器API <code>xTimerCreate</code>创建一个软件定时器，该函数会返回一个<strong>用来识别当前创建的这个定时器的句柄 timer_A</strong>，当我们调用 <code>xTimerStart</code> 启动定时器 <strong>timer_A</strong>时，函数内部实际是将<strong>START命令</strong> 和 <strong>定时器句柄timer_A</strong>封装成一个消息体，并放入定时器服务专用的<strong>消息队列 xTimerQueue</strong>中，而<strong>定时器服务任务prvTimerTask</strong>则从该消息队列中提取消息，并根据消息中的命令执行相应的动作。<br><img src="/2022/11/27/FreeRTOS-principle_of_timer/timer-task-schema.png"></p>
<p>为什么需要这种分离式的架构（为什么弄一个独立的定时器服务任务）？ 软件定时器提供了一种延后执行的功能，可以在未来某个时间执行某个动作。所以需要有相关的数据结构来维护这些信息（记录哪些时间点会有某个定时器超时，以及超时要执行的动作）。<br>这些数据结构和功能直接在内核代码中实现也是可以的，但是软件定时器并不属于内核<strong>必备功能</strong>（任务调度，时间的感知就属于内核必备功能），所以FreeRTOS将其抽离出来，单独实现在Timer.c文件中，做成一个可选功能（对于资源受限设备，并且不需要软件定时器功能时，去掉改功能可以节省ROM和RAM资源）。如果应用需要使用软件定时器时，内核启动时就会自动创建一个TimerTask任务来处理所有软件定时器相关的工作。<br>因此，我们自定义的任务需要调用软件定时相关API时，就需要和TimerTask任务进行通信，FreeRTOS中任务间通信，可以通过消息队列来实现。当然，这些通信的实现，FreeRTOS已经封装好了（即调用API时，API内部自动封装相应的消息体，并发送到消息队列中）。<br><br></p>
<h4 id="2-内核如何实现在设置的超时发生后，调用设置的回调函数"><a href="#2-内核如何实现在设置的超时发生后，调用设置的回调函数" class="headerlink" title="2 内核如何实现在设置的超时发生后，调用设置的回调函数"></a>2 内核如何实现在设置的超时发生后，调用设置的回调函数</h4><p>下文涉及到内核中的多个任务队列，如果不了解，可以先参考这篇文章<a href="https://fengxun2017.github.io/2022/11/01/FreeRTOS-task-status-management/">FreeRTOS的任务调度和管理</a></p>
<p>软件定时器模块维护了一个 定时器链表 <strong>TimerList</strong>，基于内核的<a href="https://fengxun2017.github.io/2022/11/04/FreeRTOS-kernel-list/">链表数据结构</a>实现。当调用<code>xTimerStart</code>启动一个定时器时， api内部会将 start命令+要启动的定时器 封装成一个消息体发送到到消息队列中，而软件定时器服务任务<code>TimerTask</code>则从消息队列中提取消息体，并将其中的定时器插入到定时器链表 <strong>TimerList</strong>中。大致如下图所示：<br><img src="/2022/11/27/FreeRTOS-principle_of_timer/timer-list.png"></p>
<p>定时器链表<strong>TimerList</strong> 中的每一项，维护了一个定时器的相关信息（定时器的超时时间，超时后需要调用的回调函数等）。并且，该链表是按照 定时器的超时时间 递增排序的。这样，每次判断超时时间是否到达时，只需要判断第一个即可，如果第一个定时器还未超时，则后面的均未超时。</p>
<p>在后台常驻的定时器服务任务<strong>prvTimerTask</strong>，会通过该链表来判断是否有定时器超时。<br>定时器服务 任务的大致代码逻辑如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">prvTimerTask</span><span class="params">( <span class="type">void</span> * pvParameters )</span>&#123;</span><br><span class="line">    </span><br><span class="line">    ....</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ; ; )</span><br><span class="line">    &#123;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">// 查询定时器链表的第一项，获取其中的定时器超时时间</span></span><br><span class="line">        xNextExpireTime = prvGetNextExpireTime( &amp;xListWasEmpty );</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 判断定时器是否超时，如果超时，则调用定时器回调函数</span></span><br><span class="line">        <span class="comment">// 如果没超时，则阻塞当前任务（定时器服务任务），直到超时</span></span><br><span class="line">        <span class="comment">// 或者消息队列xTimerQueue 收到新消息。</span></span><br><span class="line">        prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 处理消息队列xTimerQueue 中的定时器相关命令</span></span><br><span class="line">        prvProcessReceivedCommands();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中：</p>
<ul>
<li><p>prvGetNextExpireTime：该函数内部会查询定时器链表的第一项，获取其中的定时器超时时间。返回值<code>xNextExpireTime</code>，即链表中第一个定时器的超时时间，<code>xListWasEmpty</code>返回当前定时器链表是否为空（为空，则表示当前没有正在运行的定时器）。</p>
</li>
<li><p>prvProcessTimerOrBlockTask：该函数内部会根据是否存在定时器，以及定时器是否超时等情况，执行不同的处理过程。</p>
<ul>
<li><p><strong>情况1</strong>：如果上一步获得的<code>xListWasEmpty=pdTRUE</code>，即当前没有正在运行的定时器，那么该函数中就会一直阻塞（即软件定时器服务任务<code>prvTimerTask</code>阻塞），直到消息队列<code>xTimerQueue</code>收到消息。</p>
<p> 这是通过将当前任务（prvTimerTask）从就绪队列中移除，并挂到消息队列的<code>xTimerQueue</code>的等待消息任务链表上（xTimerQueue的成员xTasksWaitingToReceive）。其过程如下图所示：<br> <img src="/2022/11/27/FreeRTOS-principle_of_timer/timer_wait_queue.png"><br> 这样，当消息队列<code>xTimerQueue</code> 中有数据时（有新的定时器相关命令），就会可以通过<code>xTasksWaitingToReceive</code>成员，直接找到任务<code>prvTimerTask</code>，并使其恢复就绪状态。</p>
</li>
<li><p><strong>情况2</strong>：如果<code>xListWasEmpty=pdFALSE</code>，即当前有正在运行的定时器存在，并且当前时间（内部通过<code>xTaskGetTickCount()</code>获得系统当前“时间”）已经大于上一步获得的<code>xNextExpireTime</code>，则表明定时器链表中的第一个定时器已经超时了，那就就会调用定时器的超时回调函数。在函数<code>prvProcessTimerOrBlockTask</code>内部，会调用<code>prvProcessExpiredTimer</code>来处理超时的定时器，代码逻辑大致如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">prvProcessTimerOrBlockTask</span><span class="params">( <span class="type">const</span> TickType_t xNextExpireTime, BaseType_t xListWasEmpty )</span> &#123;</span><br><span class="line">    ....</span><br><span class="line">    <span class="comment">// 获取当前时间</span></span><br><span class="line">    xTimeNow = prvSampleTimeNow( &amp;xTimerListsWereSwitched );</span><br><span class="line">    <span class="comment">// 定时器链表不为空，且第一个定时器的超时时间到达了</span></span><br><span class="line">    <span class="keyword">if</span>( ( xListWasEmpty == pdFALSE ) &amp;&amp; ( xNextExpireTime &lt;= xTimeNow ) )</span><br><span class="line">    &#123;</span><br><span class="line">        ...</span><br><span class="line">        <span class="comment">// 处理超时</span></span><br><span class="line">        prvProcessExpiredTimer( xNextExpireTime, xTimeNow );</span><br><span class="line">    &#125;</span><br><span class="line">    ....</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 处理超时内部实现</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">prvProcessExpiredTimer</span><span class="params">( <span class="type">const</span> TickType_t xNextExpireTime, <span class="type">const</span> TickType_t xTimeNow )</span> &#123;</span><br><span class="line">    <span class="comment">// 超时的是定时器链表中的第一个定时器，获取它</span></span><br><span class="line">    Timer_t * <span class="type">const</span> pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); </span><br><span class="line"></span><br><span class="line">    <span class="comment">// 已经超时了，将其从定时器链表中移除</span></span><br><span class="line">    ( <span class="type">void</span> ) uxListRemove( &amp;( pxTimer-&gt;xTimerListItem ) );</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果这个定时器时周期性的定时器，那么超时后，需要重置它，让它再次开始计时。内部会将其再次插入到定时器链表TimerList中</span></span><br><span class="line">    <span class="keyword">if</span>( ( pxTimer-&gt;ucStatus &amp; tmrSTATUS_IS_AUTORELOAD ) != <span class="number">0</span> )</span><br><span class="line">    &#123;</span><br><span class="line">        prvReloadTimer( pxTimer, xNextExpireTime, xTimeNow );</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// 调用创建定时器时设置的回调函数。</span></span><br><span class="line">    pxTimer-&gt;pxCallbackFunction( ( TimerHandle_t ) pxTimer );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
<li><p><strong>情况3</strong>：如果<code>xListWasEmpty=pdFALSE</code>，即当前有定时器存在，但是当前时间（内部通过<code>xTaskGetTickCount()</code>获得系统当前“时间”）小于上一步获得的<code>xNextExpireTime</code>，则表明现在没有定时器超时。那么，当前函数<code>prvProcessTimerOrBlockTask</code> 就会阻塞（即prvTimerTask任务阻塞），直到到达超时时间<code>xNextExpireTime</code>，或者消息队列<code>xTimerQueue</code>收到消息。<br>实现原理同上，只是这里不仅将任务<code>prvTimerTask</code>挂到消息队列<code>xTimerQueue</code>的等待消息任务链表上（xTimerQueue的成员xTasksWaitingToReceive），同时还会挂到内核的<code>DelayedTaskList</code>链表（延迟任务队列）上。如下图所示：<br><img src="/2022/11/27/FreeRTOS-principle_of_timer/timer_wait_queue_or_timeout.png"><br>这样无论是定时器超时时间到达了，还是消息队列收到新消息了（定时器相关命令），任务都能恢复就绪状态，来处理超时的定时器，或处理新接收到的定时器命令。</p>
</li>
</ul>
</li>
<li><p>prvProcessReceivedCommands：检查消息队列<code>xTimerQueue</code>中是否有消息，有就提取处理，没有就立刻返回。</p>
</li>
</ul>
<br>

<h4 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h4><p>最后，再总结一下定时器工作的流程。</p>
<p>当我们在工程中配置了使用软件定时器，在<code>main</code>函数中调用启动内核调度<code>api：vTaskStartScheduler</code>后，内核就会自动创建软件定时器需要的资源，如软件定时器专用消息队列<code>xTimerQueue</code>，软件定时器服务任务<code>prvTimerTask</code>，软件定时器链表<code>TimerList</code>等。</p>
<p>当我们没有实际启动定时器时，即当前系统中没有正在运行的定时器。软件定时器服务任务<code>prvTimerTask</code>在运行后，调用<code>prvGetNextExpireTime</code>函数，查询定时器链表<code>TimerList</code>发现当前没有在运行的定时器，（进入<code>prvProcessTimerOrBlockTask</code>函数后）<code>prvTimerTask</code>任务就没有工作需要处理，那么就会将自己挂载到消息队列<code>xTimerQueue</code>的等待消息任务链表上（进入阻塞态），直到消息队列中有数据到来。—–（此时是阻塞在<code>prvProcessTimerOrBlockTask</code>函数内部）</p>
<p>某个时刻，在<strong>自定义任务A</strong> 中我们调用了<code>xTimerStart</code>来启动<strong>定时器timer_A</strong>，就会将 start命令+<strong>定时器timer_A</strong> 打包成消息体，发送到消息队列<code>xTimerQueue</code>中，消息队列收到消息后，检查到<code>prvTimerTask</code>任务在等待消息，则让<code>prvTimerTask</code>任务恢复就绪态。此时，如果<code>prvTimerTask</code>任务的优先级大于<strong>自定义的任务A</strong>，<code>prvTimerTask</code>任务就会立刻得到运行（抢占式调度）。 <code>prvTimerTask</code>任务恢复运行后（从<code>prvProcessTimerOrBlockTask</code>函数中恢复运行，并退出函数后），（进入<code>prvProcessReceivedCommands</code>函数中）从消息队列中提取消息，并将<strong>定时器timer_A</strong>插入到定时器链表上。—–（退出<code>prvProcessReceivedCommands</code>函数）</p>
<p>之后，<code>prvTimerTask</code>任务再次调用<code>prvGetNextExpireTime</code>函数，获取定时器链表中第一个定时器的超时时间，再次进入<code>prvProcessTimerOrBlockTask</code>函数中。此时，如果超时时间小于系统当前“时间”，那么就是超时了，就会执行超时回调函数。 否则，还未超时，就会将任务<code>prvTimerTask</code>同时挂到内核延迟任务队列 DelayedList，和消息队列<code>xTimerQueue</code>的等待数据任务链表上。这样无论是超时时间到达了，还是有新命令发送过来，<code>prvTimerTask</code>任务都能恢复就绪状态，继续处理后续过程。</p>
<br>
FreeRTOS交流QQ群-663806972

<br>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/" title="FreeRTOS-软件定时器的实现原理">http://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/11/16/FreeRTOS-use-timer/" rel="prev" title="FreeRTOS-软件定时器的使用">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-软件定时器的使用
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/12/01/FreeRTOS-deferring-work/" rel="next" title="FreeRTOS-延后执行机制">
                  FreeRTOS-延后执行机制 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
